﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Specialized;
using System.IO;

namespace DAL
{
    public class Polaczenie
    {
        /// ConnectionString do bazy danych
        /// </summary>
        private static string connectionString = Properties.Settings.Default.DbConnectionString;

        /// <summary>
        /// Nazwa provider-a użytej bazy danych
        /// </summary>
        private static string dbProvider = Properties.Settings.Default.DbProvider;

        private static void zmienUstawienie(string connString, string DbProv)
        {
            
            
            if (!connString.Equals(connectionString))
            {
                if (Properties.Settings.Default.DbConnectionString != null)
                    Properties.Settings.Default.DbConnectionString = connString;      
                
            }
            if (!DbProv.Equals(dbProvider))
            {
                if (Properties.Settings.Default.DbProvider !=null)
                    Properties.Settings.Default.DbProvider = DbProv;                
            }
            Properties.Settings.Default.Save();
            
            
        }

        public static bool sprPolaczenie()
        {
            NameValueCollection nvc = wczytajPlikUstawien();

            zmienUstawienie(nvc[0], nvc[1]);

            connectionString = Properties.Settings.Default.DbConnectionString;
            dbProvider = Properties.Settings.Default.DbProvider;

            DbProviderFactory provider = DbProviderFactories.GetFactory(dbProvider);
            DbConnection conn = provider.CreateConnection();
            bool jestPolaczenie = false;
            conn.ConnectionString = connectionString;

            try
            {
                conn.Open();
                jestPolaczenie = true;
            }
            catch (SqlException e)
            {
                jestPolaczenie = false;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
            return jestPolaczenie;
        }

        private static NameValueCollection wczytajPlikUstawien()
        {
            TextReader tr = new StreamReader("database.ini");

            // read a line of text
            
            string linia1 =tr.ReadLine();
            string[] linia1tab = linia1.Split('#');
            string linia2 =tr.ReadLine();
            string[] linia2tab = linia2.Split('#');

            NameValueCollection nvc = new NameValueCollection();
            nvc.Add(linia1tab[0],linia1tab[1]);
            nvc.Add(linia2tab[0],linia2tab[1]);

            return nvc;
        }
    }
}
